package tw.com.hitevision.whiteboard.android.widgets.floatView.widget.appfloat

import android.content.Context
import android.view.View
import tw.com.hitevision.whiteboard.android.widgets.floatView.WARN_REPEATED_TAG
import tw.com.hitevision.whiteboard.android.widgets.floatView.data.FloatConfig
import tw.com.hitevision.whiteboard.android.widgets.floatView.utils.Logger

internal object FloatManager {

    private const val DEFAULT_TAG = "default"
    val floatMap = mutableMapOf<String, AppFloatManager>()

    /**
     *  create FloatManager and check exist
     */
    fun create(context: Context, config: FloatConfig) = if (checkTag(config)) {
        floatMap[config.floatTag!!] = AppFloatManager(context.applicationContext, config)
            .apply { createFloat() }
    } else {
        config.callbacks?.createdResult(false, WARN_REPEATED_TAG, null)
        Logger.w(WARN_REPEATED_TAG)
    }

    /**
     * if invisible view needShow is false
     */
    fun visible(
        isShow: Boolean,
        tag: String? = null,
        needShow: Boolean = floatMap[tag]?.config?.needShow ?: true
    ) = floatMap[getTag(tag)]?.setVisible(if (isShow) View.VISIBLE else View.GONE, needShow)

    /**
     *  dismiss
     */
    fun dismiss(tag: String? = null) = floatMap[getTag(tag)]?.exitAnim()

    /**
     *  remove
     */
    fun remove(floatTag: String?) = floatMap.remove(floatTag)

    /**
     *  get tag value
     */
    fun getTag(tag: String?) = tag ?: DEFAULT_TAG

    /**
     *  get floatManager
     */
    fun getAppFloatManager(tag: String?) = floatMap[getTag(tag)]

    /**
     *  check tag
     */
    private fun checkTag(config: FloatConfig): Boolean {
        config.floatTag = getTag(config.floatTag)
        return !floatMap.containsKey(config.floatTag!!)
    }

}